package com.education.platform.management.service.impl;

import com.education.platform.common.enums.FlowBusinessTypeEnum;
import com.education.platform.common.enums.FlowTypeEnum;
import com.education.platform.common.enums.OrderStatusEnum;
import com.education.platform.common.enums.OrderTypeEnum;
import com.education.platform.common.exception.BusinessException;
import com.education.platform.common.service.impl.BaseServiceImpl;
import com.education.platform.dao.*;
import com.education.platform.dao.entity.*;
import com.education.platform.dao.model.ConsumeRecordModel;
import com.education.platform.dao.model.UserOrderModel;
import com.education.platform.management.config.ThreadUser;
import com.education.platform.management.enums.PushTypeEnum;
import com.education.platform.management.push.PushUtil;
import com.education.platform.management.service.UserOrderService;
import com.education.platform.management.vo.request.OrderDeliverVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * describe: 订单
 *
 * @author : tomato
 * @date: 2020-06-29 10:28:08.867
 **/
@Service
public class UserOrderServiceImpl extends BaseServiceImpl<UserOrderDao, UserOrderDO> implements UserOrderService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserOrderServiceImpl.class);

    @Autowired
    private UserOrderDao userOrderDao;
    @Autowired
    private OrderReceiptDao orderReceiptDao;
    @Autowired
    private AccountDao accountDao;
    @Autowired
    private AccountFlowDao accountFlowDao;
    @Autowired
    private UserBaseDao userBaseDao;
    @Autowired
    private PushUtil pushUtil;

    /**
     * 发货
     * @param deliverVO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deliver(OrderDeliverVO deliverVO) {

        UserOrderDO order = userOrderDao.getById(deliverVO.getOrderId());
        if(order == null){
            throw new BusinessException("订单不存在");
        }

        OrderReceiptDO update = new OrderReceiptDO();
        update.setLogisticsCompany(deliverVO.getLogisticsCompany());
        update.setLogisticsNo(deliverVO.getLogisticsNo());
        update.setDeliveryTime(deliverVO.getDeliveryTime());
        update.setUpdateTime(new Date());
        update.setUpdateBy(ThreadUser.getUserName());
        update.setOrderId(deliverVO.getOrderId());
        update.setDeleted(false);
        if (orderReceiptDao.deliveryByOrderId(update) != 1) {
            throw new BusinessException("操作失败");
        }
        UserOrderDO orderDO = new UserOrderDO();
        orderDO.setId(deliverVO.getOrderId());
        orderDO.setOrderStatus(OrderStatusEnum.SHIPPED.getValue());
        orderDO.setOrderStatusName(OrderStatusEnum.SHIPPED.getDes());
        orderDO.setUpdateTime(new Date());
        orderDO.setUpdateBy(ThreadUser.getUserName());
        if (userOrderDao.updateById(orderDO) != 1) {
            throw new BusinessException("操作失败");
        }
        //推送消息
//        PushUtil pushUtil = PushUtil.getInstance();
        pushUtil.push(order.getUserId(), PushTypeEnum.SEND, String.valueOf(order.getOrderNo()), order.getGoodsName());
        return Boolean.TRUE;
    }

    @Override
    public List<UserOrderModel> getOrderAndDetails(UserOrderModel query) {
        return userOrderDao.getOrderAndDetails(query);
    }

    /**
     * 查询消费记录
     *
     * @param query
     * @return
     */
    @Override
    public List<ConsumeRecordModel> getConsumeList(ConsumeRecordModel query) {
        return userOrderDao.getConsumeList(query);
    }

    /**
     * 退货
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void returnOrder(Integer id) {
        UserOrderDO userOrderDO = userOrderDao.getById(id);
        if (userOrderDO == null) {
            throw new BusinessException("订单不存在");
        }
        if (!OrderTypeEnum.OBJECT_ORDER.getValue().equals(userOrderDO.getOrderType())) {
            throw new BusinessException("实物订单才能操作");
        }
        if (!OrderStatusEnum.WAIT_DELIVER.getValue().equals(userOrderDO.getOrderStatus())) {
            throw new BusinessException("订单不是待发货状态，不能退货");
        }
        UserOrderDO updateOrder = new UserOrderDO();
        updateOrder.setId(id);
        updateOrder.setOrderStatus(OrderStatusEnum.CANCEL.getValue());
        updateOrder.setOrderStatusName(OrderStatusEnum.CANCEL.getDes());
        userOrderDao.updateById(updateOrder);

        Integer beanNumber = userOrderDO.getTotalPrice();
        Integer userId = userOrderDO.getUserId();
        AccountDO accountDO = accountDao.getByUserId(userId);
        //退回豆子
//        AccountDO
        accountDao.recharge(beanNumber, userId);
        //保存流水记录
        this.createAccountFlow(accountDO, FlowBusinessTypeEnum.RETURN_BEANS, FlowTypeEnum.IN, beanNumber, userOrderDO.getOrderNo());


    }


    private void createAccountFlow(AccountDO accountDO, FlowBusinessTypeEnum fbt, FlowTypeEnum ft, Integer flow, String returnOrderNo) {
        AccountFlowDO accountFlowDO = new AccountFlowDO();
        accountFlowDO.setUserId(accountDO.getUserId());
        accountFlowDO.setFlowNumber(flow);
        accountFlowDO.setCreateTime(new Date());
        accountFlowDO.setDeleted(false);
        accountFlowDO.setBusinessType(fbt.getValue());
        accountFlowDO.setFlowType(ft.getValue());
        accountFlowDO.setRemarks(fbt.getDes());
        accountFlowDO.setRelationNo(returnOrderNo);
        accountFlowDO.setBeforeNumber(accountDO.getBeanNumber());
        accountFlowDO.setAfterNumber(accountDO.getBeanNumber() + flow);

        accountFlowDao.insert(accountFlowDO);
    }
}
